package com.junxonline.plat.service.household.impl;

import com.junxonline.plat.dao.model.Position;
import com.junxonline.plat.dao.vo.FloorPlanVO;
import com.junxonline.plat.dao.vo.HouseholdVO;
import com.junxonline.plat.dao.vo.PageVO;
import com.junxonline.common.util.CommonUtils;
import com.junxonline.plat.dao.model.House;
import com.junxonline.plat.dao.model.Household;
import com.junxonline.plat.dao.repository.HouseholdRepository;
import com.junxonline.plat.dao.vo.QueryHouseholdVO;
import com.junxonline.plat.service.household.HouseholdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class HouseholdServiceImpl implements HouseholdService {

    @Autowired
    private HouseholdRepository householdRepository;

    /**
     * 获取住户数据
     *
     * @param vo
     * @return
     */
    @Override
    public HouseholdVO getHousehold(QueryHouseholdVO vo) {

        Household household = householdRepository.findByHouseholdId(vo.getHouseholdId());

        HouseholdVO householdVO = new HouseholdVO();

        householdVO.setHouseholdId(household.getHouseholdId());
        householdVO.setHouseholdNo(household.getHouseholdNo());
        householdVO.setHouseholdCreateTime(household.getHouseholdCreateTime());

        householdVO.setHouseholdName(household.getHouseholdName());
        householdVO.setHouseholdSex(household.getHouseholdSex());
        householdVO.setHouseholdPhone(household.getHouseholdPhone());
        householdVO.setHouseholdEmail(household.getHouseholdEmail());
        householdVO.setHouseholdJob(household.getHouseholdJob());
        householdVO.setHouseholdAge(household.getHouseholdAge());
        householdVO.setHouseholdIDCard(household.getHouseholdIDCard());
        householdVO.setHouseholdEducation(household.getHouseholdEducation());
        householdVO.setHouseholdHobby(household.getHouseholdHobby());

        // 触发懒加载
        List<Position> positions = household.getPositions();
        for (Position position : positions) {
            if (!position.getPositionType().equals(1)) {
                positions.remove(position);
            }
            else {
                householdVO.setHouseholdPositionId(position.getPositionId());
                householdVO.setHouseholdPositionName(position.getPositionName());
            }
        }

        return householdVO;
    }

    /**
     * 筛选查询住户
     *
     * @param pageVO
     * @param vo
     * @return
     */
    @Override
    public PageVO queryHousehold(PageVO pageVO, QueryHouseholdVO vo) {
        PageRequest pageRequest = PageRequest.of(pageVO.getPage() - 1, pageVO.getLimit(), new Sort(Sort.Direction.ASC, "householdId"));

        Page<Household> page = householdRepository.findAll(new Specification<Household>() {
            @Override
            public Predicate toPredicate(Root<Household> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                List<Predicate> params = new ArrayList<>();
                String householdName = vo.getHouseholdName();
                String positionName = vo.getPositionName();

                if (CommonUtils.isNotEmpty(householdName)) {
                    params.add(criteriaBuilder.like(root.get("householdName"), "%" + householdName + "%"));
                }

                if (CommonUtils.isNotEmpty(positionName)) {

                    ListJoin<Household, Position> join = root.join(root.getModel().getList("positions",Position.class), JoinType.LEFT);
                    params.add(criteriaBuilder.like(join.get("positionName"), "%" + positionName + "%"));
                }

                params.add(criteriaBuilder.equal(root.get("isHousehold"), 1));

                return criteriaBuilder.and(params.toArray(new Predicate[params.size()]));
            }
        }, pageRequest);

        List<HouseholdVO> householdsVOs = new ArrayList<>();
        List<Household> households = page.getContent();

        for (Household household : households) {

            // 替换住户性别
            switch (household.getHouseholdSex()) {
                case 0:
                    household.setHouseholdSexString("男");
                    break;
                case 1:
                    household.setHouseholdSexString("女");
                    break;
                default:
                    break;
            }

            HouseholdVO householdVO = new HouseholdVO();

            householdVO.setHouseholdId(household.getHouseholdId());
            householdVO.setHouseholdNo(household.getHouseholdNo());
            householdVO.setHouseholdCreateTime(household.getHouseholdCreateTime());

            householdVO.setHouseholdName(household.getHouseholdName());
            householdVO.setHouseholdSex(household.getHouseholdSex());
            householdVO.setHouseholdSexString(household.getHouseholdSexString());
            householdVO.setHouseholdPhone(household.getHouseholdPhone());
            householdVO.setHouseholdEmail(household.getHouseholdEmail());
            householdVO.setHouseholdJob(household.getHouseholdJob());
            householdVO.setHouseholdAge(household.getHouseholdAge());
            householdVO.setHouseholdIDCard(household.getHouseholdIDCard());
            householdVO.setHouseholdEducation(household.getHouseholdEducation());
            householdVO.setHouseholdHobby(household.getHouseholdHobby());

            // 处理部门
            List<Position> positions = household.getPositions();

            if (CommonUtils.isNotEmpty(positions)) {
                householdVO.setHouseholdPositionId(positions.get(0).getPositionId());
                householdVO.setHouseholdPositionName(positions.get(0).getPositionName());
            }

            householdsVOs.add(householdVO);

        }

        pageVO.setTotal(page.getTotalElements());
        pageVO.setData(householdsVOs);

        return pageVO;
    }

    /**
     * 添加住户
     *
     * @param vo
     * @return
     */
    @Override
    public boolean addHousehold(HouseholdVO vo) {

        StringBuilder householdNO = new StringBuilder();
        householdNO.append("UIDNO");

        Household tempHousehold = householdRepository.findByHouseholdIdLast();
        if (CommonUtils.isEmpty(tempHousehold)) {
            householdNO.append("000001");
        }
        else {
            DecimalFormat decimalFormat = new DecimalFormat("000000");
            String currentNO = tempHousehold.getHouseholdId().toString();
            String nextNO = decimalFormat.format(Integer.parseInt(currentNO) + 1);
            householdNO.append(nextNO);
        }

        Household household = new Household();

        household.setHouseholdNo(householdNO.toString());
        household.setHouseholdCreateTime(new Date());
        household.setIsHousehold(1);
        household.setIsWorker(0);

        household.setHouseholdName(vo.getHouseholdName());
        household.setHouseholdSex(vo.getHouseholdSex());
        household.setHouseholdPhone(vo.getHouseholdPhone());
        household.setHouseholdEmail(vo.getHouseholdEmail());
        household.setHouseholdJob(vo.getHouseholdJob());
        household.setHouseholdAge(vo.getHouseholdAge());
        household.setHouseholdIDCard(vo.getHouseholdIDCard());
        household.setHouseholdEducation(vo.getHouseholdEducation());
        household.setHouseholdHobby(vo.getHouseholdHobby());

        household = householdRepository.save(household);

        // 添加部门
        householdRepository.saveHousePositionIn(household.getHouseholdId(), vo.getHouseholdPositionId());

        return true;
    }

    /**
     * 修改住户
     *
     * @param vo
     * @return
     */
    @Override
    public boolean editHousehold(HouseholdVO vo) {

        Household tempHousehold = householdRepository.findByHouseholdId(vo.getHouseholdId());

        tempHousehold.setHouseholdName(vo.getHouseholdName());
        tempHousehold.setHouseholdSex(vo.getHouseholdSex());
        tempHousehold.setHouseholdPhone(vo.getHouseholdPhone());
        tempHousehold.setHouseholdEmail(vo.getHouseholdEmail());
        tempHousehold.setHouseholdJob(vo.getHouseholdJob());
        tempHousehold.setHouseholdAge(vo.getHouseholdAge());
        tempHousehold.setHouseholdIDCard(vo.getHouseholdIDCard());
        tempHousehold.setHouseholdEducation(vo.getHouseholdEducation());
        tempHousehold.setHouseholdHobby(vo.getHouseholdHobby());

        householdRepository.save(tempHousehold);

        // 如果住户有部门先删除住户原有的部门
        List<Map<String, BigInteger>> householdPositions = householdRepository.findHousePositionByHouseholdId(vo.getHouseholdId());

        for (Map<String, BigInteger> householdPosition : householdPositions) {
            BigInteger householdId = householdPosition.get("household_id");
            BigInteger positionId = householdPosition.get("position_id");
            householdRepository.deleteHouseholdPositionIn(householdId.longValue(), positionId.longValue());
        }

        // 再添加部门
        if (CommonUtils.isNotEmpty(vo.getHouseholdPositionId())) {
            householdRepository.saveHousePositionIn(vo.getHouseholdId(), vo.getHouseholdPositionId());
        }

        return true;
    }

    /**
     * 删除住户
     *
     * @param householdIds
     * @return
     */
    @Override
    public boolean delHousehold(Long[] householdIds) {

        List<Household> households = householdRepository.findByHouseholdIdIn(householdIds);

        for (Household household : households) {

            List<Position> positions = household.getPositions();

            // 删除与该住户相关联的中间表的所有部门岗位数据
            for (Position position : positions) {
                Long positionId = position.getPositionId();
                householdRepository.deleteHouseholdPositionIn(household.getHouseholdId(), positionId);
            }

            List<House> houses = household.getHouses();

            // 删除与该住户相关联的中间表的所有房产数据
            for (House house : houses) {
                householdRepository.deleteHouseholdHouseIn(household.getHouseholdId(), house.getHouseId());
            }

            // 再删除住户
            householdRepository.delete(household);

        }

        return true;

    }

}
